import React from 'react';
import { toJS }from 'mobx';
import { inject, observer } from 'mobx-react';
import { Flex, Icon, Toast } from 'weaver-mobile';
import { MapPage, Upload, Signature } from 'weaver-mobile-page';
import { withRouter } from 'react-router-dom';
import base from "../../util/base";
import * as SignUtil from '../../util/SignUtil';
import * as VariableKeys from '../../constants/variableKey';
import * as AdapterConstant from '../../constants/adapter';
import * as mobx from "mobx";
import * as EmSDK from '../../util/emSDK';
import SoundInput from './SoundInput';
import { getLabel } from "../../util/common";


@inject('wfSignInputStore','wfOperateStore')
@withRouter
@observer
export default class SignMore extends React.Component {
    constructor(props){
        super(props);
    }

    judgeEmBottomBtn = () => {
        const { variableMap } = this.props.wfSignInputStore;
        let isShowEmBottomBtn = variableMap.get("isShowEmBottomBtn")||false;
        let emBottomBtn = EmSDK.judgeApiSupport('showBottomToolBar') || false;
        return  isShowEmBottomBtn && emBottomBtn;
    }
     
    render() {
        const { signatureRoute, isForwad , variableMap} = this.props.wfSignInputStore;
        const { markInfo = {} } = this.props.wfOperateStore;
        const {remarkInfo={}}=markInfo;
        const btns = this.getMoreBtnDatas();
        const row1Btns = btns.length > 4 ? btns.slice(0, 4) : btns;
        const row2Btns = btns.length > 4 ? btns.slice(4, btns.length) : [];
        let datas = [row1Btns];
        if (row2Btns.length > 0) datas.push(row2Btns);
        let value = isForwad ? (variableMap.get(VariableKeys.FORWARD_SIGN_HANDWRITTEN+"_datasAndUrls")||{}) : (variableMap.get(VariableKeys.SIGN_HANDWRITTEN+"_datasAndUrls")||{})
        const {modeType={}, signHandWrittenColor, signHandWrittenBrush }=value;
        const { handwritingType="h5" } = remarkInfo;
        return (
            <div className={'wf-sign-input-more-info'}>
                {datas.map((row, rowIndex) => {
                    return (
                        <div key={`row_${rowIndex}`} className={'more-info-row'}>
                            {
                                row.length > 0 && row.map((item, index) => {
                                    const { icon = '', classname = '', title = '', showDot = false, key, iconCom } = item;
                                    if (key == 2) {
                                        return (
                                            <div key={`col_${index}`} className={'more-info-col'}
                                                onClick={() => this.moreBtnClick(key, showDot)}>
                                                <div className={`item-icon ${classname}`}>
                                                    {showDot && <div className={'item-dot'} />}
                                                    <Signature store={signatureRoute}
                                                        className="wf-Signature"
                                                        onChange={this.SignatureOnChange}
                                                        value={toJS(value) || {}}
                                                        needMergePicker={true}
                                                        needTrim={true}
                                                        devType={handwritingType}
                                                        color={modeType.color||signHandWrittenColor}
                                                        mode={modeType.mode || "1"}
                                                        brush={modeType.brush||signHandWrittenBrush}
                                                        onEmSuccess={this.onHandWrittenEmSuccess}
                                                        inherit={showDot||false}
                                                        isShowEmBottomBtn = {this.judgeEmBottomBtn()}
                                                        onOk={()=>{}}
                                                    >
                                                        {iconCom ? iconCom : <Icon type={icon} />}
                                                    </Signature>
                                                </div>
                                                <div className={'item-title'}>{title}</div>
                                            </div>
                                        )
                                    } else {
                                        return (
                                            <div key={`col_${index}`} className={'more-info-col'}
                                                onClick={() => this.moreBtnClick(key, showDot)}>
                                                <div className={`item-icon ${classname}`}>
                                                    {showDot && <div className={'item-dot'} />}
                                                    {iconCom ?
                                                        iconCom
                                                        :
                                                        <Icon type={icon} />
                                                    }

                                                </div>
                                                <div className={'item-title'}>{title}</div>
                                            </div>
                                        )
                                    }

                                })
                            }
                        </div>
                    )
                })}
                <SoundInput />
            </div>
        )
    }

    SignatureOnChange = (result, mode) => {
        const { saveSignAnnex, isForwad, controlVariableMap } = this.props.wfSignInputStore;
        let key  = isForwad ? VariableKeys.FORWARD_SIGN_HANDWRITTEN+"_datasAndUrls" : VariableKeys.SIGN_HANDWRITTEN+"_datasAndUrls";
        let key_fileid = isForwad ? VariableKeys.FORWARD_SIGN_HANDWRITTEN : VariableKeys.SIGN_HANDWRITTEN;
        result.modeType = mode;
        const cb = () =>{
            this.props.history.go(-1);
        }
        if(result.isEmpty == true){
            controlVariableMap(key, result)
            controlVariableMap(key_fileid, [])
            cb();
        }else{
            let _result = JSON.stringify(result);
            controlVariableMap(key, result) 
            Toast.loading('Loading...', 0);
            saveSignAnnex(3, _result,cb) 
        }
    }
    onHandWrittenEmSuccess=(res)=>{
        const { saveSignAnnex, isForwad, controlVariableMap,variableMap } = this.props.wfSignInputStore;
        if(typeof res =="string"){
            res = JSON.parse(res);
        }
        const { localData = '' } = res;
        const handlewritingKey = isForwad ? VariableKeys.FORWARD_SIGN_HANDWRITTEN : VariableKeys.SIGN_HANDWRITTEN;

        if(localData){
            let param={url:`data:image/png;base64,`+localData}
            saveSignAnnex(3, JSON.stringify(param));
            controlVariableMap("localExist",true)
        }else{
           variableMap.delete(handlewritingKey)
           controlVariableMap("localExist",false)
        }
    }

    getMoreBtnDatas() {
        const wfOperateStore = base.wfOperateStore;
        const { markInfo = {} } = wfOperateStore;
        const signParams = mobx.toJS(markInfo);

        const {remarkInfo={}}=signParams;
        const {handwritingType="h5", handWrittenSignSwitchMobile }=remarkInfo;
        const isShowHandWritten = handwritingType=="h5"||(window.em&&window.em.checkJsApi&&window.em.checkJsApi("handleWriting"));
        const isEm = handwritingType=="em"&&(window.em&&window.em.checkJsApi&&window.em.checkJsApi("handleWriting"));
        const { isSignDoc_edit = false, isSignWorkflow_edit = false, isannexupload_edit = false, annexmaxUploadImageSize = 5, isSignLocation_edit = false } = signParams;

        const { wfSignInputStore } = this.props;
        const { isForwad, Adapter, variableMap } = wfSignInputStore;
        const wfReplaceDataKey = isForwad ? VariableKeys.FORWARD_SIGN_WF_REPLACE_DATAS : VariableKeys.SIGN_WF_REPLACE_DATAS;
        const docReplaceDataKey = isForwad ? VariableKeys.FORWARD_SIGN_DOC_REPLACE_DATAS : VariableKeys.SIGN_DOC_REPLACE_DATAS
        const annexDataKey = isForwad ? VariableKeys.FORWARD_SIGN_ANNEX_DOC_INFOS : VariableKeys.SIGN_ANNEX_DOC_INFOS;
        const soundResourceKey = isForwad ? VariableKeys.FORWARD_SIGN_SPEECH_ATTCHMENT_DATAS : VariableKeys.SIGN_SPEECH_ATTCHMENT_DATAS;
        const remarkLocationKey = isForwad ? VariableKeys.FORWARD_REMARK_LOCATION : VariableKeys.SIGN_REMARK_LOCATION;
        const handlewritingKey = isForwad ? VariableKeys.FORWARD_SIGN_HANDWRITTEN : VariableKeys.SIGN_HANDWRITTEN;
        const fulltextannotationKey = isForwad ? VariableKeys.FORWARD_SIGN_FULL_TEXT_ANNOTATION : VariableKeys.SIGN_FULL_TEXT_ANNOTATION;

        const remarkLoactionData = SignUtil.getVariableMapVal(remarkLocationKey, {});
        const handleWrigingData = SignUtil.getVariableMapVal(handlewritingKey, {});
        const signworkflowreplacedata = SignUtil.getVariableMapVal(wfReplaceDataKey, []);
        const signdocreplacedata = SignUtil.getVariableMapVal(docReplaceDataKey, []);
        const annexData = SignUtil.getVariableMapVal(annexDataKey, []);
        const soundDatas = SignUtil.getVariableMapVal(soundResourceKey, []);
        const fulltextannotationDatas = SignUtil.getVariableMapVal(fulltextannotationKey, []);
        const fileUploading = SignUtil.getVariableMapVal(VariableKeys.SIGN_FILE_UPLOADING, false);
        const localExist = SignUtil.getVariableMapVal("localExist", false)
        let isShowHandWrittenDot = false;
        if(((isEm && localExist) || !isEm) && (handleWrigingData && Object.keys(handleWrigingData).length > 0)){
            isShowHandWrittenDot=true;
        }
        const btns = [];
        Adapter.judgeApiSupport(AdapterConstant.API_EDIT_IMAGE) && btns.push({
            icon: 'postil',
            'classname': 'postil-icon',
            title: getLabel(129658, "全文批注"),
            showDot: fulltextannotationDatas && fulltextannotationDatas.length > 0,
            key: '1'
        });
        false && isShowHandWritten && handWrittenSignSwitchMobile == 1 &&
        btns.push({
            icon: 'sign',
            'classname': 'sign-icon',
            title: getLabel(25349, '手写签批'),
            showDot: isShowHandWrittenDot,
            key: '2'
        });
        isSignWorkflow_edit && btns.push({
            icon: 'flow',
            'classname': 'flow-icon',
            title: getLabel(30045, '流程'),
            showDot: signworkflowreplacedata && signworkflowreplacedata.length > 0,
            key: '3'
        });
        isSignDoc_edit && btns.push({
            icon: 'file',
            'classname': 'file-icon',
            title: getLabel(22243, '文档'),
            showDot: signdocreplacedata && signdocreplacedata.length > 0,
            key: '4'
        });
        Adapter.judgeApiSupport(AdapterConstant.API_VOICE) && btns.push({
            icon: 'speech-input-big',
            'classname': 'speech-icon',
            title: getLabel(128154, '语音'),
            showDot: soundDatas && soundDatas.length > 0,
            key: '5'
        });
        isSignLocation_edit && Adapter.judgeApiSupport(AdapterConstant.API_POSITION) && btns.push({
            icon: 'location',
            'classname': 'location-icon',
            title: getLabel(22981, '位置'),
            showDot: Object.keys(remarkLoactionData).length > 0,
            key: '6'
        });
        let iconCom;
        //如果还在上传中状态卸载Upload组件会导致onUploading事件不执行
        if (annexData.length > 0 && !fileUploading) {
            iconCom = <Icon type={'annex-big'} />
        } else {
            //附件拖拽相关控制开始，
            const { remarkInfo = {}, annexmainId, annexsubId, annexsecId } = signParams;
            const { isdragula = false, isrename = false } = remarkInfo;
            const category = `${annexmainId},${annexsubId},${annexsecId}`;
            let uploadParams = {};
            if (isdragula || isrename) {
                uploadParams = { "isFirstUploadFile": "9" }
            }
            iconCom = (<Upload onChange={this.doChangeEvent.bind(this)}
                maxUploadSize={annexmaxUploadImageSize}
                uploadParams={uploadParams}
                multiSelection={true}
                onUploading={(type) => SignUtil.onUploading(type, 'signMore')}
                uploadUrl={'/api/doc/upload/uploadFile2Doc?category=' + category}
            >
                <Icon type={'annex-big'} />
            </Upload>);
        }
        isannexupload_edit && btns.push({
            icon: 'annex-big',
            'classname': 'annex-icon',
            title: getLabel(156, '附件'),
            showDot: annexData && annexData.length > 0,
            key: '7',
            iconCom
        });
        return btns;
    }

    moreBtnClick(key, showDot) {
        const { wfSignInputStore, history } = this.props;
        const { remarkWfStore, remarkDocStore, positionStore, Adapter, isForwad, controlVariableMap } = wfSignInputStore;

        const wfOperateStore = base.wfOperateStore;
        const { markInfo = {} } = wfOperateStore;
        const signParams = mobx.toJS(markInfo);
        const { isSignDoc_edit = false, isSignWorkflow_edit = false, isannexupload_edit = false, annexsecId = '' } = signParams;
        const f_weaver_belongto_userid  = markInfo.fileuserid || '';
        const f_weaver_belongto_usertype  = markInfo.fileloginyype == '1' ? '0' : '1';

        switch (key) {
            case '1':
                const fulltextannotationKey = isForwad ? VariableKeys.FORWARD_SIGN_FULL_TEXT_ANNOTATION : VariableKeys.SIGN_FULL_TEXT_ANNOTATION;
                const fulltextannotationDatas = SignUtil.getVariableMapVal(fulltextannotationKey, []);
                if (fulltextannotationDatas.length > 0) {
                    history.push("/req/formAnnotationList");
                } else {
                    Adapter.editImage();
                }
                return;
            case '2':
                // Adapter.judgeApiSupport(AdapterConstant.API_HANDLE_WRITING) ? Adapter.handleWriting(showDot) :"";//客户端手写签批用
                return;
            case '3':
                remarkWfStore.searchParams = {...remarkWfStore.searchParams,f_weaver_belongto_userid:f_weaver_belongto_userid,f_weaver_belongto_usertype:f_weaver_belongto_usertype}
                history.push(remarkWfStore.path);
                return;
            case '4':
                history.push(remarkDocStore.path);
                return;
            case '5':
                const soundResourceKey = isForwad ? VariableKeys.FORWARD_SIGN_SPEECH_ATTCHMENT_DATAS : VariableKeys.SIGN_SPEECH_ATTCHMENT_DATAS;
                const soundDatas = SignUtil.getVariableMapVal(soundResourceKey, []);
                if (soundDatas.length > 0) {
                    history.push('/req/soundList');
                } else {
                    Adapter.voice();
                }
                return;
            case '6':
                const locationKey = isForwad ? VariableKeys.FORWARD_REMARK_LOCATION : VariableKeys.SIGN_REMARK_LOCATION;
                const locationdata = SignUtil.getVariableMapVal(locationKey, {});
                Adapter.getLocation(locationdata);
                return;
            case '7':
                const annexDataKey = isForwad ? VariableKeys.FORWARD_SIGN_ANNEX_DOC_INFOS : VariableKeys.SIGN_ANNEX_DOC_INFOS;
                const annexData = SignUtil.getVariableMapVal(annexDataKey, []);
                if (annexData.length > 0) {
                    history.push('/req/annexList');
                }
                return;
        }
    }

    doChangeEvent(ids, filedatas) {
        const { wfSignInputStore } = this.props;
        const { isForwad, controlVariableMap } = wfSignInputStore;
        const annexdocinfoKey = isForwad ? VariableKeys.FORWARD_SIGN_ANNEX_DOC_INFOS : VariableKeys.SIGN_ANNEX_DOC_INFOS;
        const annexData = SignUtil.getVariableMapVal(annexdocinfoKey, []);
        const __annexData = annexData.concat(filedatas)
        controlVariableMap(annexdocinfoKey, __annexData);
    }
}